package com.camera.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.camera.Exception.ServiceException;
import com.camera.common.FileUtils;
import com.camera.common.HttpClient;
import com.camera.common.ResultData;
import com.camera.config.StorageProperties;
import com.camera.pojo.CameraDTO;
import com.camera.service.CameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;


/**
 * @Classname CameraServiceImpl
 * @Description TODO
 * @Date 2025/3/10 14:03
 * @Created by xxx
 */
@Service
public class CameraServiceImpl implements CameraService {
    @Autowired
    private StorageProperties storageProperties;

    @Override
    public ResultData getType(CameraDTO cameraDTO) throws Exception {
        String imagesURL = cameraDTO.getImagesURL();
        String imageID = cameraDTO.getImageID();
        Path saveDir = Paths.get(storageProperties.getPath());
        Files.createDirectories(saveDir);
        Path savePath = HttpClient.downloadWithProperExt(imageID, imagesURL, saveDir.toString());
        File file = new File(savePath.toString());
        if (!file.exists()) {
            throw new ServiceException("图片下载失败");
        }
        byte[] bytes = Files.readAllBytes(savePath);
        String fileToBase64 = Base64.getEncoder().encodeToString(bytes);
        Map<String, String> requestMap = new HashMap<>();
        requestMap.put("imageID", imageID);
        requestMap.put("image", fileToBase64);
        String result = HttpClient.doPOST(storageProperties.getRequestUrl(), requestMap);
/*
        String result = "{"
                + "\"imageID\":\"549518729\","
                + "\"result\":\"nvr\","
                + "\"code\":0,"
                + "\"msg\":\"success\""
                + "}";
*/
        if (result.isEmpty() || result == null) {
            throw new ServiceException("请求失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String code = jsonObject.getString("code");
        ResultData resultData = new ResultData();
        resultData.setImageID(imageID);
        if (code.equals("0")) {
            resultData.setResult(jsonObject.getString("result"));
        } else {
            throw new ServiceException(jsonObject.getString("message"));
        }
        String type = jsonObject.getString("result");
        if (storageProperties.isEnableSaveFile()) {
            Path saveFilePath = Paths.get(saveDir.toString(), type, file.getName());
            Files.createDirectories(saveFilePath.getParent());
            FileUtils.saveImage(savePath, saveFilePath);
        }
        return resultData;
    }

}
